import json
from typing import Any, List

from playwright.sync_api import Page


class LocalStorage:
    def __init__(self, page: Page):
        self.page = page
        pass

    def get_storage(self, key: str, format_type=''):
        value = self.page.evaluate(f'localStorage.getItem("{key}")')
        if format_type == 'json':
            value = json.loads(value)
        return value

    def set_storage(self, key: str, value: Any):
        if isinstance(value, dict):
            value = json.dumps(value)
        self.page.evaluate(f'localStorage.setItem("{key}", "{value}")')
        pass

    def clear_storage(self):
        self.page.evaluate('localStorage.clear()')
        pass

    def get_json_storage(self, key: str):
        value = self.get_storage(key, format_type='json')
        return value

    def set_json_storage(self, key: str, value: Any):
        if isinstance(value, dict):
            value = json.dumps(value)
        self.page.evaluate(f'localStorage.setItem("{key}", "{value}")')
        pass

    def get_storage_keys(self):
        keys = self.page.evaluate('Object.keys(localStorage)')
        return keys

    def clear_storage_keys(self, keys: List[str]):
        for key in keys:
            self.page.evaluate(f'localStorage.removeItem("{key}")')
        pass

    def clear_all_storage(self):
        self.page.evaluate('localStorage.clear()')
        pass 